<?php
defined('SWAP_ROOT') or die('非法操作');
function cd_sfyz_read() {
    import("swap.Mail");

}
function cd_sfyz_randStr($len = 6) {
    $chars = 'ABDEFGHJKLMNPQRSTVWXYabdefghijkmnpqrstvwxy23456789';
    mt_srand((double)microtime()*1000000*getmypid());
    $password = '';
    while (strlen($password) < $len)
        $password.= substr($chars,(mt_rand()%strlen($chars)),1);
    return $password;
}
class cd_sfyz extends controller
{
    function config() {
        SMACSQL()->query("CREATE TABLE IF NOT EXISTS `用户实名认证插件` (`id` INT NOT NULL AUTO_INCREMENT , `uid` INT NOT NULL , `open` TEXT NOT NULL , `name` TEXT NOT NULL , `city` TEXT NOT NULL , `sex` TEXT NOT NULL , `age` TEXT NOT NULL , `idcard` TEXT NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");
        //open 1是认证了  0是取消认证了
        //找不到uid是没认证

        return array(
            'swap_no_login' => array(
                'index' => '0',
                'mail' => '0',
                'set' => '1',
                'lists' => '1'
            ),
            'index' => '1',
            'mail' => '1',
            'set' => '0',
            'lists' => '0'
        );
    }
function set() {
		need_admin();
		$plugbsz="cd_sfyz";
		$plugname="实名认证插件设置";
		$moshi=mac_url_get(1);
		if($moshi==""){$moshi="list";}
		$id="";$id=mac_url_get(2);
		$ok="";$ok=mac_url_get(3);
		//die("{$moshi},{$id},{$ok}");
		$userarray2	=array(
            array('扣除费用','text','不能为空，不能小于零，可以等于0'),
            array('api接口','text','直接填写<br>https://service-hsyjtg0f-1301232119.bj.apigw.tencentcs.com/release/id/check<br>或者是腾讯提供的'),
            array('SecretID','text','腾讯控制台内提供'),
            array('SecretKey','text','腾讯控制台内提供'),
            array('描述','text','前台显示，比如会扣费，比如姓名和身份证不一致也会扣扣费'),
        );
		if($moshi=="editok"){
			foreach( $userarray2 as $hehehi1 => $hehehi2){plug_eva($plugbsz,$hehehi2[0],_POST($hehehi2[0]));}
			die("修改完成ok");
		}

			AdminT::header($plugname, '');
        AdminT::search();
        echo '<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script><script src="https://www.layuicdn.com/layer/layer.js"></script><main class="page-content content-wrap">';
        AdminT::navbar();
        AdminT::sidebar();
        echo '<div class="page-inner">';
			AdminT::title($plugname, '<li>网站设置</li>');
					?>	
<div id="main-wrapper" class="container"><div class="row"><div class="col-md-12"><div class="panel panel-primary"><div class="panel-body"><form role="form" id="settingfrom" class="form-horizontal form-groups-bordered">

<?php
	foreach( $userarray2 as $hehehi1 => $hehe){
		$hehe[3]=plug_eva($plugbsz,$hehe[0]);
		if($hehe[1]=='text'){
			$nrhtml="<input type=\"{$hehe[1]}\" value=\"{$hehe[3]}\" name=\"{$hehe[0]}\" class=\"form-control\">";
		}elseif($hehe[1]=='yesno' ){
			if($hehe[3]=='on'){$hehe['yes_yesno']='checked="checked"';} else{$hehe['no_yesno']='checked="checked"';}
			$nrhtml="<label><input type=\"radio\" name=\"{$hehe[0]}\" value=\"on\"{$hehe['yes_yesno']}/ >是 </label><label><input type=\"radio\" name=\"{$hehe[0]}\" value=\"off\" {$hehe['no_yesno']} />否</label> ";
		}else{$nrhtml="{$hehe[1]}-{$hehe[3]}";}
		echo("<div class=\"form-group\"><label class=\"col-sm-3 control-label\">{$hehe[0]}</label><div class=\"col-sm-5\">{$nrhtml}{$hehe[2]}</div></div>");
	}
	?> <div class="form-group"><div class="col-sm-offset-3 col-sm-5"><a href="javascript:void(0)" onclick="$.post('/index.php/plugin/<?php echo $plugbsz ;?>/set/editok/',$('#settingfrom').serialize(),function(data){if(data.match('ok')=='ok')  layer.alert('保存成功'); else swap_alert('error','保存失败',data);});" class="btn btn-success">保存更改</a></div></div></form></div></div></div></div></div></div><?php


		
        AdminT::page_footer();
        echo '</div></main>';
        AdminT::cd_nav();
        AdminT::pjs();
        echo '<script src="https://dn-idcswap-down.qbox.me/assets/plugins/waypoints/jquery.waypoints.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/jquery-counterup/jquery.counterup.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/toastr/toastr.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/flot/jquery.flot.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/flot/jquery.flot.time.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/flot/jquery.flot.symbol.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/flot/jquery.flot.resize.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/flot/jquery.flot.tooltip.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/curvedlines/curvedLines.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/metrojs/MetroJs.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/morris/raphael.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/morris/morris.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/js/modern.min.js"></script><script src="https://dn-idcswap-down.qbox.me/assets/plugins/datatables/js/jquery.dataTables.min.js"></script><script>var extable;$(document).ready(function() {extable=$(\'#example\').DataTable({"language":{"url":"https://cdn.datatables.net/plug-ins/e9421181788/i18n/Chinese.json"}});});</script></body></html>';
    }
    function lists() {
        need_admin();
        AdminT::header('实名认证信息列表', '<link href="/admin_assets/plugins/datatables/css/jquery.datatables.min.css" rel="stylesheet" type="text/css"/><link href="/admin_assets/plugins/datatables/css/jquery.datatables_themeroller.css" rel="stylesheet" type="text/css"/>');
        AdminT::search(); ?><main class="page-content content-wrap">
		<?php
        AdminT::navbar();
        AdminT::sidebar(); ?><div class="page-inner"><?php
        AdminT::title('实名认证信息列表', '<li>网站设置</li>'); ?>
						
		<div id="main-wrapper" class="container">

			<div class="row"><div class="col-md-12"><div class="panel panel-white">
			
			         
<table id="example" class="display table" style="width: 100%; cellspacing: 0;">
	<thead><tr><th>id</th><th>用户id</th><th>姓名</th><th>身份证</th><th>性别</th><th>年龄</th><th>城市</th></tr></thead>

	<tbody>
<?php
        $this->conn->select('用户实名认证插件', '*', "");
        while ($cp = $this->conn->fetch_assoc()) {
            echo "<tr><td>{$cp['id']}</td><td>{$cp['uid']}</td><td>{$cp['name']}</td><td>{$cp['idcard']}</td><td>{$cp['sex']}</td><td>{$cp['age']}</td><td>{$cp['city']}</td></tr>";
        } ?>	</tbody>
</table>

		</div>
		</div></div></div><?php
        AdminT::page_footer(); ?></div></main>';<?php
        AdminT::cd_nav();
        AdminT::pjs(); ?><script src="/admin_assets/plugins/waypoints/jquery.waypoints.min.js"></script>
		<script src="/admin_assets/plugins/jquery-counterup/jquery.counterup.min.js"></script>
		<script src="/admin_assets/plugins/toastr/toastr.min.js"></script>
		<script src="/admin_assets/plugins/flot/jquery.flot.min.js"></script>
		<script src="/admin_assets/plugins/flot/jquery.flot.time.min.js"></script>
		<script src="/admin_assets/plugins/flot/jquery.flot.symbol.min.js"></script>
		<script src="/admin_assets/plugins/flot/jquery.flot.resize.min.js"></script>
		<script src="/admin_assets/plugins/flot/jquery.flot.tooltip.min.js"></script>
		<script src="/admin_assets/plugins/curvedlines/curvedLines.js"></script>
		<script src="/admin_assets/plugins/metrojs/MetroJs.min.js"></script>
		<script src="/admin_assets/plugins/morris/raphael.min.js"></script>
		<script src="/admin_assets/plugins/morris/morris.min.js"></script>
		<script src="/admin_assets/js/modern.min.js"></script>
		<script src="/admin_assets/plugins/datatables/js/jquery.dataTables.min.js"></script>
		<script>var extable;$(document).ready(function() {extable=$('#example').DataTable({"language":{"url":"https://cdn.datatables.net/plug-ins/e9421181788/i18n/Chinese.json"}});});</script></body></html>
		<?php
    }
    
    function index() {
        $username = _POST('username');
        if (!empty($username)) {
            $this->conn->select('用户','*',"用户名='".$username."' OR 电子邮件='".$username."'");
            if ($this->conn->db_num_rows() == 0)
                exit(redirect($this->cakurl().'/plugin/cd_sfyz/index/?error='.$this->lang['不存在的用户名或邮箱']));
            $array = $this->conn->fetch_array();
            $code = cd_sfyz_randStr();
            cd_sfyz_read();
            plug_eva('cd_sfyz','邮件码:'.$code,$array['uid']);
            $lang = plug_lang_get('cd_sfyz','mail');
            $lang['内容'] = str_replace('{<code>}',$code,$lang['内容']);
            SendMail($array['电子邮件'],$lang['标题'],$lang['内容'],$lang['发信人']);
            exit(redirect($this->cakurl().'/plugin/cd_sfyz/index/?success='.$this->lang['页面通知']));
        }
        TEMPLATE::display('index.tpl');
    }

    function mail() {
        $secretId_plug_eva = plug_eva('cd_sfyz',"SecretID");
        $secretKey_plug_eva = plug_eva('cd_sfyz',"SecretKey");
        $url_plug_eva = plug_eva('cd_sfyz',"api接口");
        $money_sf_plug_eva = plug_eva('cd_sfyz',"扣除费用");
        $about_some_plug_eva = plug_eva('cd_sfyz',"描述");
        TEMPLATE::assign('about_some', $about_some_plug_eva);
        $code = _POST('code');
        $name = _POST('name');
        $idcard = _POST('idcard');
        if (!empty($code)) {
            $uid = plug_eva('cd_sfyz','邮件码:'.$code);
            if (empty($uid)) {
                exit(redirect($this->cakurl().'/plugin/cd_sfyz/mail/?error='.$this->lang['验证码不正确或不存在']));
            } else {


                $secretId = $secretId_plug_eva;
                $secretKey = $secretKey_plug_eva;
                $source = 'market';
                $datetime = gmdate('D, d M Y H:i:s T');
                $signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
                $sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
                $auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
                $method = 'GET';
                $headers = array(
                    'X-Source' => $source,
                    'X-Date' => $datetime,
                    'Authorization' => $auth,
                );
                $queryParams = array (
                    'cardNo' => $idcard,
                    'realName' => $name,
                );
                $bodyParams = array ();
                $url = $url_plug_eva;
                if (count($queryParams) > 0) {
                    $url .= '?' . http_build_query($queryParams);
                }
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
                    return $k . ': ' . $v;
                }
                    , array_values($headers), array_keys($headers)));
                if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
                }
                $data = curl_exec($ch);
                if (curl_errno($ch)) {
                    echo "Error: " . curl_error($ch);
                } else {
                    $txapi_data_array = json_decode($data,true);
                    var_dump($txapi_data_array);
                    $api_return_pd = $txapi_data_array['reason'];
                    if ($api_return_pd == '成功') {
                        $to_mysql_pd = $txapi_data_array['result']['isok'];
                        if ($to_mysql_pd == true) {
                            $name = $txapi_data_array['result']['realname'];
                            $idcard = $txapi_data_array['result']['idcard'];
                            $city = $txapi_data_array['result']['IdCardInfor']['area'];
                            $sex = $txapi_data_array['result']['IdCardInfor']['sex'];
                            $age = $txapi_data_array['result']['IdCardInfor']['birthday'];

                            $money_sf = $money_sf_plug_eva;
                            $uid = User::Uid();
                            $userbccdalao = D()->query("select * from 用户 where uid={$uid}");
                            $dataArray = array(); 
                            while ($row = D()->fetch_array($userbccdalao)) {
                                $dataArray[10] = $row;
                            }
                            $real_zcsj = $dataArray[10][预存款];
                            if ($real_zcsj - $money_sf >= 0) {
                                D()->update('用户',"预存款='".((float)$real_zcsj-((float)$money_sf))."'","uid='{$uid}'");
                                D()->insert('用户实名认证插件', "`uid` ,`open`,`name` ,`city` ,`sex` ,`age` ,`idcard` ", "'$uid' ,'1' ,'$name' ,'$city' ,'$sex' ,'$age' ,'$idcard'");
                                plug_eva('cd_sfyz','邮件码:'.$code,NULL);
                                $this->conn->delete('插件配置',"插件名称='cd_sfyz' and 值='".$uid."'");
                                exit(header('Location://'.$_SERVER['HTTP_HOST'].'/index.php/plugin/cd_sfyz/mail/?success=实名认证成功'));
                            } else {
                                plug_eva('cd_sfyz','邮件码:'.$code,NULL);
                                $this->conn->delete('插件配置',"插件名称='cd_sfyz' and 值='".$uid."'");
                                exit(header('Location://'.$_SERVER['HTTP_HOST'].'/index.php/plugin/cd_sfyz/mail/?error=您的账户余额不足'));
                            }
                        } else {
                            $money_sf = plug_eva('cd_sfyz',"扣除费用");
                            $uid = User::Uid();
                            $userbccdalao = D()->query("select * from 用户 where uid={$uid}");
                            $dataArray = array();
                            while ($row = D()->fetch_array($userbccdalao)) {
                                $dataArray[10] = $row;
                            }
                            $real_zcsj = $dataArray[10][预存款];
                            if ($real_zcsj - $money_sf >= 0) {
                                D()->update('用户',"预存款='".((float)$real_zcsj-((float)$money_sf))."'","uid='{$uid}'");
                                plug_eva('cd_sfyz','邮件码:'.$code,NULL);
                                $this->conn->delete('插件配置',"插件名称='cd_sfyz' and 值='".$uid."'");
                                exit(header('Location://'.$_SERVER['HTTP_HOST'].'/index.php/plugin/cd_sfyz/mail/?error=实名认证失败'));
                            } else {
                                plug_eva('cd_sfyz','邮件码:'.$code,NULL);
                                $this->conn->delete('插件配置',"插件名称='cd_sfyz' and 值='".$uid."'");
                                exit(header('Location://'.$_SERVER['HTTP_HOST'].'/index.php/plugin/cd_sfyz/mail/?error=您的账户余额不足'));
                            }
                        }
                    }
                    curl_close($ch);
                }
            }
        }
        $uids = User::Uid();

        $CD_sfyz_sql_pd = D()->query("select * from 用户实名认证插件 where uid={$uids}");
        $CD_sfyz_sql_pd_fatch = D()->fetch_assoc();


        TEMPLATE::assign('idcard_rz', $CD_sfyz_sql_pd_fatch);
        TEMPLATE::display('mail.tpl');
    }


}
?>